package com.example.exceltosqlite.ui.sqldao;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.exceltosqlite.R;
import com.example.exceltosqlite.base.BaseActivity;
import com.example.exceltosqlite.bean.MyConstant;
import com.example.exceltosqlite.dao.ExcelFileDao;
import com.example.exceltosqlite.dao.ExcelFileNumberDao;
import com.example.exceltosqlite.dao.ExcelFileTypeDao;
import com.example.exceltosqlite.entity.SqliteFileEntity;
import com.example.exceltosqlite.entity.SqliteFileNumberEntity;
import com.example.exceltosqlite.entity.SqliteFileTypeEntity;
import com.example.exceltosqlite.ui.sqldao.insert.SqlInsertActivity;
import com.example.exceltosqlite.ui.sqldao.update.SqlUpdateActivity;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.FileOutputStream;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SqliteDaoActivity extends BaseActivity {

    @BindView(R.id.typeSP1)
    Spinner typeSP1;
    @BindView(R.id.numberSP1)
    Spinner numberSP1;
    @BindView(R.id.sqliteLV)
    ListView sqliteLV;
    @BindView(R.id.bt4)
    Button bt4;
    @BindView(R.id.dateTV)
    TextView dateTV;
    @BindView(R.id.bt1)
    Button bt1;
    @BindView(R.id.bt2)
    Button bt2;
    @BindView(R.id.bt3)
    Button bt3;

    private SpinnerTypeAdapter spinnerTypeAdapter;
    private SpinnerNoAdapter spinnerNoAdapter;
    private SpinnerFileAdapter spinnerFileAdapter;
    private ExcelFileTypeDao excelFileTypeDao;
    private ExcelFileNumberDao excelFileNumberDao;
    private ExcelFileDao excelFileDao;
    private String intentPath = "";
    private SqliteFileTypeEntity curSqliteFileTypeEntity; //当前选中的  type表数据
    private SqliteFileNumberEntity curSqliteNumberEntity; //当前选中的   number表数据


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sqlite_dao);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        init();
    }


    private void init() {
        excelFileTypeDao = new ExcelFileTypeDao(this);
        excelFileNumberDao = new ExcelFileNumberDao(this);
        excelFileDao = new ExcelFileDao(this);
        spinnerNoAdapter = new SpinnerNoAdapter(this);
        spinnerTypeAdapter = new SpinnerTypeAdapter(this);
        spinnerFileAdapter = new SpinnerFileAdapter(this);
        intentPath = getIntent().getStringExtra(MyConstant.STR_NAME_1);
        Log.e("bugggg","intentPath = " + intentPath);
        typeSP1.setAdapter(spinnerTypeAdapter);
        typeSP1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                curSqliteFileTypeEntity = (SqliteFileTypeEntity) parent.getItemAtPosition(position);
                addMessageNo();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });
        try {
            List<SqliteFileTypeEntity> sqliteFileTypeEntityList = excelFileTypeDao.queryAll();
            if (null != sqliteFileTypeEntityList && 0 != sqliteFileTypeEntityList.size()) {
                spinnerTypeAdapter.setItems(sqliteFileTypeEntityList);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }


        numberSP1.setAdapter(spinnerNoAdapter);
        numberSP1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                curSqliteNumberEntity = (SqliteFileNumberEntity) parent.getItemAtPosition(position);
                queryAllDatas();
                dateTV.setText("创建时间：" + curSqliteNumberEntity.getDate());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }

        });

        sqliteLV.setAdapter(spinnerFileAdapter);
        sqliteLV.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                SqliteFileEntity item = (SqliteFileEntity) parent.getItemAtPosition(position);
                try {
                    excelFileDao.delete(item);
                    spinnerFileAdapter.getItems().remove(item);
                    spinnerFileAdapter.notifyDataSetChanged();
                    Toast.makeText(SqliteDaoActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return true;
            }
        });

    }


    private void addMessageNo() {
        try {
            List<SqliteFileNumberEntity> sqliteFileNumberEntityList = excelFileNumberDao.queryAll("typeID", curSqliteFileTypeEntity.getId() + "");
            spinnerNoAdapter.setItems(sqliteFileNumberEntityList);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }


    private void queryAllDatas() {
        try {
            List<SqliteFileEntity> sqliteFileEntityList = excelFileDao.queryAll("messageID", curSqliteNumberEntity.getId() + "");
            if (null != sqliteFileEntityList && 0 != sqliteFileEntityList.size()) {
                spinnerFileAdapter.setItems(sqliteFileEntityList);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    @OnClick({R.id.bt1, R.id.bt2, R.id.bt4})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.bt1:
                if (null == curSqliteFileTypeEntity || null == curSqliteNumberEntity) {
                    Toast.makeText(this, "当前没有可操作的报文，请先导入", Toast.LENGTH_SHORT).show();
                    return;
                }
                intent = new Intent(this, SqlInsertActivity.class);
                intent.putExtra(MyConstant.STR_NAME_1, curSqliteFileTypeEntity.getType());
                intent.putExtra(MyConstant.STR_NAME_2, curSqliteNumberEntity);
                startActivity(intent);
                break;
            case R.id.bt2:
                if (null == curSqliteFileTypeEntity || null == curSqliteNumberEntity) {
                    Toast.makeText(this, "当前没有可操作的报文，请先导入", Toast.LENGTH_SHORT).show();
                    return;
                }
                intent = new Intent(this, SqlUpdateActivity.class);
                intent.putExtra(MyConstant.STR_NAME_1, curSqliteFileTypeEntity);
                intent.putExtra(MyConstant.STR_NAME_2, curSqliteNumberEntity);
                intent.putExtra(MyConstant.STR_NAME_3, (Serializable) spinnerFileAdapter.getItems());
                startActivity(intent);
                break;
            case R.id.bt3:
                if (null == curSqliteFileTypeEntity || null == curSqliteNumberEntity) {
                    Toast.makeText(this, "当前没有可操作的报文，请先导入", Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(this, "长按下方的item直接删除", Toast.LENGTH_SHORT).show();
                break;
            case R.id.bt4:
                if (null == curSqliteFileTypeEntity || null == curSqliteNumberEntity) {
                    Toast.makeText(this, "当前没有可操作的报文，请先导入", Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    int tempTypeKEey = excelFileTypeDao.queryKey(curSqliteFileTypeEntity.getType() + ""); //type的主键
                    List<SqliteFileNumberEntity> tempSqliteFileNumberEntities = excelFileNumberDao.queryAll("typeID", tempTypeKEey + "", "messageNo", curSqliteNumberEntity.getMessageNo());
                    SqliteFileNumberEntity tempSqliteFileNumberEntity = tempSqliteFileNumberEntities.get(0);
                    List<SqliteFileEntity> tempSqliteFileEntityList;
                    tempSqliteFileEntityList = excelFileDao.queryAll("messageID", tempSqliteFileNumberEntity.getId() + "");
                    createExcel(curSqliteFileTypeEntity.getType() + "", tempSqliteFileNumberEntity.getMessageNo(), tempSqliteFileNumberEntity.getMessageName(), tempSqliteFileEntityList);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                break;
        }
    }


    /**
     * 写文件
     */
    public void createExcel(String pType, String pNumber, String pName, List<SqliteFileEntity> sqliteFileEntityList) {
        try {
            if (null == sqliteFileEntityList || 0 == sqliteFileEntityList.size()) {
                Toast.makeText(this, "暂无可导出文件", Toast.LENGTH_SHORT).show();
                return;
            }
            FileOutputStream fileOut = new FileOutputStream(intentPath.replace(".xls", "_new.xls"));
            Workbook book = new XSSFWorkbook();
            Sheet sheet = book.createSheet("Sheet1"); // 工作簿的名称
            Row row0 = sheet.createRow(0);
            row0.createCell(0).setCellValue(pType);
            row0.createCell(1).setCellValue(pNumber);
            row0.createCell(2).setCellValue(pName);
            for (int i = 0; i < sqliteFileEntityList.size(); i++) {
                Row row = sheet.createRow(i+1);
                row.createCell(0).setCellValue(sqliteFileEntityList.get(i).getCol00());
                row.createCell(1).setCellValue(sqliteFileEntityList.get(i).getCol01());
                row.createCell(2).setCellValue(sqliteFileEntityList.get(i).getCol02());
                row.createCell(3).setCellValue(sqliteFileEntityList.get(i).getCol03());
                row.createCell(4).setCellValue(sqliteFileEntityList.get(i).getCol04());
                row.createCell(5).setCellValue(sqliteFileEntityList.get(i).getCol05());
                row.createCell(6).setCellValue(sqliteFileEntityList.get(i).getCol06());
                row.createCell(7).setCellValue(sqliteFileEntityList.get(i).getCol07());
                row.createCell(8).setCellValue(sqliteFileEntityList.get(i).getCol08());
                row.createCell(9).setCellValue(sqliteFileEntityList.get(i).getCol09());
            }
            book.write(fileOut);
            book.close();
            Toast.makeText(this, "导出成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            System.out.println(e);
            Toast.makeText(this, "导出失败" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Subscribe
    public void onEvent(String str) {
        if (MyConstant.EVENT_MSG_2.equals(str)) {
            queryAllDatas();
            return;
        }
        if (MyConstant.EVENT_MSG_3.equals(str)) {
            finish();
            return;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }
}
